import { createSlice } from "@reduxjs/toolkit";

const counter = createSlice({
  name: "counter",
  initialState: {
    count: 0,
    list: [],
  },
  // 内置了 immutable.js、redux-thunk
  reducers: {
    add(state, action) {
      state.count++;
    },
    sub(state) {
      state.count--;
    },
    pus(state) {
      state.list.push(Math.floor(Math.random() * 100));
    },
    del(state, action) {
      state.list.splice(action.payload, 1);
    },
  },
});

export const { add, sub, pus, del } = counter.actions;

// 定义异步 action
export const subAsync = (payload) => {
  return (dispatch, getState) => {
    setTimeout(() => {
      dispatch(sub());
    }, 2000);
  };
};

export default counter.reducer;
